import type { RouteLocationNormalizedGeneric, Router } from "vue-router"
import { useAppStore } from "@/store"
import { isEmpty, useCommonLoadingBar } from "@/utils"
import { isRefreshRoute } from "@/hooks/refresh"
import { useAuthStore, useTabViewStore, useThemeStore } from "@/store"
import { checkLogin, hasToken } from "@/hooks/authorization"

// const NotFoundPageRoute = {
//     path: "/:path(.*)*",
//     name: "ErrorPage",
//     component: Layout,
//     meta: {
//         title: "未找到页面"
//     },
//     children: [
//         {
//             path: "/:path(.*)*",
//             name: "PageNotFound",
//             component: () => import("@/views/exception/404.vue"),
//             meta: {
//                 title: "未找到页面",
//                 needLogin: true
//             }
//         }
//     ]
// }

/**
 * 定义路由守卫
 */
export function setupRouterGuards(router: Router) {
    const loadingBar = useCommonLoadingBar()

    /**
     * 前置拦截器
     */
    router.beforeEach(async to => {
        console.log("开始导航 => " + to.fullPath)
        loadingBar.start()
        // 重定向
        if (isRefreshRoute(to)) {
            return
        }
        // 不需要登录校验的，直接转向
        const needLogin = determineNeedLogin(to)

        if (!needLogin) {
            return
        }
        const authStore = useAuthStore()

        // 登录校验
        if (!hasToken.value) {
            authStore.logout()
            return { name: "Login" }
        }
        if (authStore.isLogin) {
            return
        }
        await checkLogin()

        // 添加404
        // const isErrorPage = router.getRoutes().findIndex(item => item.name === "PageNotFound")
        // if (isErrorPage === -1) {
        //     router.addRoute(NotFoundPageRoute)
        // }

        return { path: to.path, replace: true }
    })

    /**
     * 后置拦截器
     */
    router.afterEach(to => {
        setWindowsTitle(to)
        loadingBar.finish()
        addCacheQueue(to)
    })

    /**
     * 错误拦截器
     */
    router.onError(error => {
        loadingBar.error()
        console.error(error, "路由错误")
    })
}

/**
 * 根据 router.meta.needLogin 判断是否需要登录校验
 */
function determineNeedLogin(router: RouteLocationNormalizedGeneric): boolean {
    let needLogin
    const matched = router.matched
    if (isEmpty(matched)) {
        return true
    }
    const length = matched.length
    for (let i = length; i > 0; i--) {
        const { meta = {} } = matched[i - 1]
        if (meta && Reflect.has(meta, "needLogin")) {
            needLogin = meta.needLogin
            break
        }
    }
    return needLogin !== false
}

/**
 * 动态修改标题
 */
function setWindowsTitle(to: RouteLocationNormalizedGeneric) {
    const title = useTitle()
    const routeTitle = to.meta.title as string
    const appStore = useAppStore()
    if (routeTitle) {
        title.value = `${routeTitle}-${appStore.viewTitle}`
    } else {
        title.value = appStore.viewTitle
    }
}

function addCacheQueue(to: RouteLocationNormalizedGeneric) {
    const { useTabView } = useThemeStore()
    const tabViewStore = useTabViewStore()
    if (useTabView) {
        !isRefreshRoute(to) && tabViewStore.addCacheQueue(to)
    } else {
        tabViewStore.clearCacheQueue()
    }
}
